<?php


namespace App\Services;


use App\Models\Kpi;
use App\Utils\Code;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use \Illuminate\Database\Eloquent\Builder;

class KpiService extends BaseService
{
    /**
     * 创建数据
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function store(array $params) {
        if (!$this->checkParams($params)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        return DB::transaction(function () use ($params){
            $model = new Kpi();
            if (Kpi::where('kpi_date', $params['kpi_date'])->first()) {
                throw new \Exception('该月份绩效信息已经存在', Code::EXIST_REPEAT);
            }
            $model->kpi_date = $params['kpi_date'];
            if (isset($params['kpi_value']) && is_numeric($params['kpi_value'])){
                $model->kpi_value = $params['kpi_value'];
            }
            if (isset($params['kpi_rate']) && is_numeric($params['kpi_rate'])){
                $model->kpi_rate = $params['kpi_rate'];
            }
            $model->save();
            return $model;
        });
    }

    /**
     * 数据信息
     * @param $id
     * @param bool $simple
     * @param bool $abnormal
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function show($id, $abnormal = true) {
        $model = Kpi::where('id', $id)->first();
        if (!$model && $abnormal){
            throw new \Exception('不存在的ID', Code::EMPTY_DATA);
        }
        return $model;
    }

    /**
     * 更新数据
     * @param $id
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function update($id, array $params) {
        if (!$this->checkParams($params, true)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        return DB::transaction(function () use ($id, $params){
            $model = $this->show($id);
            if (isset($params['kpi_value']) && is_numeric($params['kpi_value'])){
                $model->kpi_value = $params['kpi_value'];
            }
            if (isset($params['kpi_rate']) && is_numeric($params['kpi_rate'])){
                $model->kpi_rate = $params['kpi_rate'];
            }
            $model->save();
            return $this->show($id);
        });
    }

    /**
     * 删除数据
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function destroy(array $ids = []) {
        if (!$this::$admin) {
            throw new \Exception('你没有权限进行删除', Code::LACK_OF_CONDITIONS);
        }
        return DB::transaction(function () use ($ids) {
            return Kpi::whereIn('id', $ids)->delete();
        });
    }

    /**
     * 数据分页
     * @param array $params
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function lists(array $params = []) {
        $model = new Kpi();
        if (isset($params['kpi_date']) && $params['kpi_date']) {
            $model = $model->where('kpi_date', $params['kpi_date']);
        }
        $lists = $model->orderBy('id', 'desc')->get();
        return $lists;
    }

    public function summary(array $params = []) {
        if (isset($params['kpi_date']) && $params['kpi_date']) {
            $model = Kpi::where('kpi_date', $params['kpi_date'])->first();
        } else {
            throw new \Exception('请选择月份', Code::PARAMETER_ERROR);
        }
        if (!$model) {
            $data = [
                'kpi_date' => $params['kpi_date'],
                'kpi_value' => 0,
                'kpi_rate' => 0
            ];
        } else {
            $data = [
                'id' => $model->id,
                'kpi_date' => $params['kpi_date'],
                'kpi_value' => $model->kpi_value,
                'kpi_rate' => $model->kpi_rate
            ];
        }
        $firstDay = date('Y-m-01', strtotime($params['kpi_date']));
        $lastDay = date('Y-m-t', strtotime($params['kpi_date']));
        $tasks = DB::table('tasks')
            ->where('pinggu_status', 1)
            ->where('pinggu_date', '>=', $firstDay)
            ->where('pinggu_date', '<=', $lastDay)
            ->select(DB::raw('sum(number3) as kpi_point'))
            ->get();
        $data['kpi_point'] = $tasks[0]->kpi_point;
        return $data;
    }

    /**
     * 验证参数
     * @param array $params
     * @param bool $isUpdate
     * @return array
     * @throws \Exception
     */
    private function checkParams(array $params, $isUpdate = false){
        $rules = [
            'kpi_date' => ['bail', 'required', 'date'],
            'kpi_value' => ['bail', 'nullable', 'numeric'],
            'kpi_rate' => ['bail', 'nullable', 'numeric']
        ];
        if ($isUpdate){
            // 删除必选条件
            foreach ($rules as $field => &$rule){
                if (isset($rule[1]) && $rule[1] == 'required') {
                    unset($rule[1]);
                }
            }
        }
        $validator = Validator::make($params, $rules, [], [
            'kpi_date' => '绩效月份',
            'kpi_value' => '本月总业绩',
            'kpi_rate' => '奖金比例'
        ]);
        if ($validator->fails()) {
            throw new \Exception($validator->errors()->first(), Code::PARAMETER_ERROR);
        }
        return $params;
    }
}
